<template>

    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 5px;">
    <el-button type="text" :disabled="!isEditable" @click="addRoles" >
        <el-icon><Plus /></el-icon>
        新增角色
    </el-button>
    </div>  
    <el-table
        :data="rolesData"
        style="width: 100%"
        row-key="id"
        border
        clearable
    >
        <el-table-column prop="name" label="角色名称" />
        <el-table-column prop="description" label="角色描述" />
        <el-table-column prop="createdAt" label="创建时间" />
        <el-table-column prop="updatedAt" label="更新时间" />
        <el-table-column label="操作" width="160" align="center">
        <template #default="scope">
            <el-button
            type="primary"
            :icon="Edit"
            size="small"
            :disabled="!isEditable"
            @click="openEditDialog(scope.row)"
            title="编辑角色"
            >编辑</el-button>
            <el-button
            type="danger"
            :icon="Edit"
            size="small"
            :disabled="!isEditable"
            @click="removeRoles(scope.row)"
            title="删除角色"
            >删除</el-button>
        </template>
        </el-table-column>
  </el-table>
    <el-dialog v-model="dialogFormVisible" title="新增角色" width="500px">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="form.name" placeholder="请输角色名称" />
        </el-form-item>
        <el-form-item label="角色描述" prop="path">
          <el-input v-model="form.description" placeholder="请输描述信息" />
        </el-form-item>
        
      </el-form>

      <template #footer>
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
    <el-dialog
    v-model="dialogEditVisible"
    :title="修改角色"
    width="500px"
    >
    <el-form :model="form" label-width="80px" >
        <el-form-item label="角色名称">
        <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="角色描述">
        <el-input v-model="form.description" />
        </el-form-item>
    </el-form>
    <template #footer>
        <el-button @click="dialogEditVisible = false">取消</el-button>
        <el-button type="primary" @click="saveUpdateRoles">保存</el-button>
    </template>
    </el-dialog>
</template>
<script setup>

import {toRefs,onBeforeMount,onMounted,reactive,ref,computed} from "vue"
import { ElMessage,ElForm, ElFormItem, ElInput, ElButton,ElMessageBox } from 'element-plus';
import { Plus,Minus } from '@element-plus/icons-vue'
import { getRolesListInfoHandler,addRolesListInfoHandler,updateRolesListInfoHandler,delRolesListInfoHandler } from "../../api/roles.js"
import { base64Decode } from "../../utils/base64.js"
const data = reactive({
    rolesData: [{ "name": "", "description": "","createdAt":"","updatedAt":""}]
})
const isEditable = ref(true)
const dialogFormVisible = ref(false)
const dialogEditVisible = ref(false)
const {rolesData} = toRefs(data)
const formRef = ref(null)

const form = ref({
  id: null,
  name: '',
  description: null,
  createdAt: "",
  updatedAt: "",
})
// 过滤出主类型，避免选择子类型方法
// function getRootType(treeData) {
//  return treeData
//    .filter(item => Number(item.parent_id) === 0)
//    .map(item => {
//      return {
//        ...item,
//        children: [] // 清空子节点，只显示一级
//      }
//    })
// }
const loadConfig = async()=>{
    try {
        const response = await getRolesListInfoHandler()
        if (response?.data?.data) {
            const result = response.data.data;
            const base64String = result.queryData;
            const decodedBytes = atob(base64String);
            const uint8Array = new Uint8Array(decodedBytes.split('').map(c => c.charCodeAt(0)));

            // 使用 setTimeout 将解码和处理放到异步队列中
            setTimeout(() => {
                const decoder = new TextDecoder("utf-8");
                const decodedString = decoder.decode(uint8Array);
                console.log("Decoded string:", decodedString);

                rolesData.value = JSON.parse(decodedString);
                console.log("Menus Data:", rolesData.value);
            }, 0);  // 延迟 0 毫秒，实际上会在当前事件循环之后执行

        }
    }
    catch(error){
        console.error("获取角色数据失败:", error)
        ElMessage({
                    message: error?.response?.data?.message || "查询失败------，请重试",
                    type: 'error',
        })
    }
}
const addRoles=()=>{
    form.value = {
      name: '',
      description: null,
    }
    dialogFormVisible.value=true
}
const submitForm = async() => {
    try{
        const valid = await formRef.value.validate()
        if(valid){
            console.log('新增角色数据:', form.value)
            const res = await addRolesListInfoHandler(form.value)
            if (res.data) {
                console.log("res.data====20250821",res.data)
                ElMessage({
                message: res.data.message,
                type: 'success'})
            }
            dialogFormVisible.value = false
            await loadConfig()
        }
    } catch(error){
        console.error("添加失败:", error)
        ElMessage({
                    message: error?.response?.data?.message || "添加失败，请重试",
                    type: 'error',
        })
    }
  
}
const removeRoles=async(row)=>{
    try {
        
        await ElMessageBox.confirm(
          `确认要删除【${row.name}】吗？`,
          '删除确认',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        )
        console.log("id=======20250813",row.id)
        const intId = Number(row.id)
        const response = await delRolesListInfoHandler(intId)
        
        if (response.data) {
            ElMessage({
                    message: response.data.message,
                    type: 'success',
            })
            console.log("delcategoryData==========20250821",response.data)
            await loadConfig()
            
        }
    } catch(error) {
        console.error("删除失败:", error)
        ElMessage({
                    message: error?.response?.data?.message || "删除失败，请重试",
                    type: 'error',
        })
        // throw err // 如果需要让调用方知道错误
    }
    
}
const openEditDialog=(row)=>{
    console.log("row======20250813",row)
    form.value={...row}
    dialogEditVisible.value = true
}
const saveUpdateRoles=async()=>{
    try {
        const id=form.value.id
        console.log("==============20250822",id)

        const res = await updateRolesListInfoHandler(id,form.value)
        if (res?.data){
            ElMessage({
                    message: res.data.message,
                    type: 'success',
            })
            console.log("updatetypeData==========20250822",res.data)
            dialogEditVisible.value = false
            await loadConfig()
        }
    }catch(error){
        console.error("更新失败:", error)
        ElMessage({
                    message: error?.response?.data?.message || "更新失败，请重试",
                    type: 'error',
        })
    }
}
onMounted(()=>{
  loadConfig()
})
</script>